package org.wutopia.labcloud.domain.order.mq.consumer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.seata.rm.tcc.api.BusinessActionContext;
import org.apache.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;
import org.wutopia.labcloud.domain.order.constant.OrderStatusType;
import org.wutopia.labcloud.domain.order.dao.OrderMainDao;
import org.wutopia.labcloud.domain.order.dao.OrderProductRDao;
import org.wutopia.labcloud.domain.order.dao.entity.OrderMain;
import org.wutopia.labcloud.domain.order.dao.entity.OrderProductR;
import org.wutopia.labcloud.service.api.service.dubbo.DubboUserService;
import org.wutopia.labcloud.service.api.service.dubbo.dto.input.UserInsertNotificationInputDTO;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
@RocketMQMessageListener(
        topic = "ORDER-TOPIC",
        selectorExpression = "delivered",  // 消费多个Tag
        consumerGroup = "order-consumer-group"
)
public class OrderDeliveredConsumer implements RocketMQListener<Long> {


    private OrderMainDao orderMainDao;

    private OrderProductRDao orderProductRDao;


    @DubboReference
    private DubboUserService dubboUserService;

    @Override
    @GlobalTransactional
    public void onMessage(Long orderId) {
        log.info("收到订单超时消息: ID={}", orderId);

        OrderMain orderMain = orderMainDao.selectById(orderId);
        // 订单送达
        // 1. 修改订单状态
        UpdateWrapper<OrderMain> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", orderId);
        updateWrapper.set("status", OrderStatusType.UNCONFIRMED);
        orderMainDao.update(updateWrapper);

        // 2. 如果用户在线 通知用户

        // 模拟生成 取件码
        Random rand = new Random();
        // 生成4位随机整数（1000~9999）
        int fourDigit = rand.nextInt(9000) + 1000; // [0,9000) + 1000 → [1000, 9999][3,6](@ref)
        // 生成1位随机整数（0~9）
        int one = rand.nextInt(10) + 1;
        int two = rand.nextInt(10) + 1;

        String pickUpCode = one + "-" + two + "-" + fourDigit;
        String title = "到货通知";
        String content = "取件码为" + pickUpCode;
        String msg = title + "  " + content;
        dubboUserService.sendOnLineMsg(orderMain.getUserId(), msg);

        // 3. 发送离线用户通知信息
        UserInsertNotificationInputDTO dto = new UserInsertNotificationInputDTO();
        dto.setUserId(orderMain.getUserId());
        dto.setTitle(title);
        dto.setContent(content);
        dubboUserService.sendOffLineNotification(dto);
    }
}
